/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
    }
}

function removeElements(head: ListNode | null, val: number): ListNode | null {
    let nowNode = head; // 当前所在节点
    let preNode = nowNode; // 上一节点
    while(nowNode) {
        if (nowNode.val === val) {
            if (nowNode === head) { // 处于首个节点
                head = head.next;
                nowNode = head;
                preNode = head;
            } else { // 处于中间节点
                // todo 为什么这里的preNode可能为空
                // preNode.next = nowNode.next;
                // reason ts可能还不太智能，可加类型断言解决或类型缩小
                (preNode as ListNode).next = nowNode.next;
                // if (preNode) {
                //     preNode.next = nowNode.next;
                // }
                nowNode = nowNode.next;
            }
        } else {
            preNode = nowNode;
            nowNode = nowNode.next;
        }
    }
    return head
};